package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.DateUtil;
import io.netty.handler.codec.DateFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Component
public class UserXxlJob {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 每日工单量列表初始化
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) {
        try {
            //查询所有人员
            List<UserEntity> list = userService.list();
            list.forEach(user -> {
                //非管理员 运营/运维人员创建对应的redis集合
                if (!user.getRoleCode().equals("1001")) {
                    //设置redis对应的key
                    String key = VMSystem.REGION_TASK_KEY_PREF +
                            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "."
                            + user.getRegionId() + "." + user.getRoleCode();
                    //初始化对应区域人员列表
                    redisTemplate.opsForZSet().add(key, String.valueOf(user.getId()), 0);
                    //设置有效时间
                    redisTemplate.expire(key, Duration.ofDays(1));
                }
            });
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            return ReturnT.FAIL;
        }
    }
}
